package com.dc.commons.jpa.specification;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

import com.dc.commons.persistence.able.TreeAble;
import com.dc.commons.status.DataStatus;
import com.google.common.collect.Lists;

/*******************************************************************************<P>
 * 文件名: SpecificationHelper.java <br>
 * 版本: 1.0<br>
 * 描述:<br>
 * 版权所有: <br>
 * <P>
 * 创建者: 王建栋 <br>
 * 创建日期: 2016年6月23日 下午1:44:54<br>
 * 修改者: <br>
 * 修改日期: <br>
 * 修改说明: <br>
 ******************************************************************************/
public class SpecificationHelper {

	public static <T>Specification<T> treeSpecification(final String parentKey,final Integer displayNo){
		return new Specification<T>() {
			@Override
			public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
					CriteriaBuilder builder) {
				List<Predicate> predicates=Lists.newArrayList();
				Path<String> parentKeyPath=root.get("parentKey");
				predicates.add(builder.equal(parentKeyPath, parentKey));
				if(displayNo!=0){
					Path<Integer> displayNoPath=root.get("displayNo");
					predicates.add(builder.ge(displayNoPath, displayNo));
				}
				return builder.and(predicates.toArray(new Predicate[predicates.size()]));
			}
			
		};
	}
	
	public static <T>Specification<T> dataStatusValid(){
		return new Specification<T>() {
			@Override
			public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
					CriteriaBuilder builder) {
				List<Predicate> predicates=Lists.newArrayList();
				Path<?> expression=root.get("dataStatus");
				predicates.add(builder.equal(expression, DataStatus.VALID));
				 return builder.and(predicates.toArray(new Predicate[predicates.size()]));
			}
			
		};
	}
	
}
